package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     *
     * @param addressBook
     */
    public void add(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);

        addressBookMapper.insert(addressBook);
    }

    /**
     * 根据用户id返回用户所有地址
     *
     * @return
     */
    @Override
    public List<AddressBook> getAll() {
        Long userId = BaseContext.getCurrentId();

        List<AddressBook> list = addressBookMapper.getByUserId(userId);
        return list;
    }

    /**
     * 条件查询
     * @param addressBook
     * @return
     */
    public List<AddressBook> list(AddressBook addressBook) {
        return addressBookMapper.list(addressBook);
    }

    /**
     * @param addressBook
     */
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据地址id返回地址数据
     *
     * @param id
     * @return
     */
    public AddressBook getById(Long id) {

        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    /**
     * 根据id设置为默认地址，并将原默认地址取消默认
     * @param addressBook
     */
    public void starOrStop(AddressBook addressBook) {
       //取消原id默认地址
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressBooks = addressBookMapper.getByDefault(userId);
        addressBooks.forEach(addr -> {
            addr.setIsDefault(0);
            addressBookMapper.update(addr);
        });

        //将此id设为默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }
    /**
     * 根据id删除地址
     *
     * @param id
     */
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }
}
